package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;

import com.heima.article.service.ApArticleService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;


    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        List<ApArticle> apArticleList = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticleList);
    }

    @Override
    public ResponseResult load2(ArticleHomeDto dto, boolean firstPage) {
        if (firstPage){
            String tag = dto.getTag();
            String getPage = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + tag);
            if (StringUtils.isNotBlank(getPage)){
                HotArticleVo hotArticleVo = JSON.parseObject(getPage, HotArticleVo.class);
                return ResponseResult.okResult(hotArticleVo);

            }
        }

        return load(dto);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }
    @Override
    public ResponseResult loadnew(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 2);
        return ResponseResult.okResult(apArticles);
    }


    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private FreemarkerGenerator freemarkerGenerator;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private MinIoTemplate minIoTemplate;
    @Autowired
    private CacheService cacheService;
    @Override
    @Async
    public void generate(Long articleId) {
        LambdaQueryWrapper<ApArticleContent>wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId,articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
        if (apArticleContent ==null){
            log.warn("文章不存在");
            return;
        }
        Map<String, Object> map = new HashMap<>(1);
        map.put("content",apArticleContent.getContent());

        InputStream is = freemarkerGenerator.generate("article.ftl", map);
        String url = minIoTemplate.uploadFile("", articleId + ".html", is, "html");

        ApArticle apArticle =apArticleMapper.selectById(articleId);
        if (apArticle==null){
            log.warn("文章内容为空");
            return;
        }
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);

    //发送消息，创建索引
        //todo
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {
        String content = dto.getContent();
        ApArticle apArticle = new ApArticle();
        //获取id
        Long id = dto.getId();
        //判空
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //0判断是新增或者是修改
        if (id ==null){
            //1.id为空进入新增
            //1.1 插入article表
            int insertResult = apArticleMapper.insert(apArticle);
            if (insertResult < 1){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"新增失败");
            }
            //1.2插入article_config表
            ApArticleConfig config = new ApArticleConfig();
            config.setIsDown(false);
            config.setArticleId(apArticle.getId());
            config.setIsForward(true);
            config.setIsDelete(false);
            config.setIsComment(true);
            //保存
            int configInsertResult = apArticleConfigMapper.insert(config);
            //如果小于1，配置表插入失败
            if (configInsertResult < 1){
                log.warn("配置表插入失败");
                throw new RuntimeException("配置表插入失败");
            }
            //1.3插入article_content表

            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(content);
            //保存
            int contentInsertResult = apArticleContentMapper.insert(apArticleContent);
            if (contentInsertResult < 1){
                log.warn("内容表插入失败");
                throw new RuntimeException("内容表插入失败");
            }
            //返回id
            return ResponseResult.okResult(apArticle.getId());
        }
        else {
            //2.id存在用修改
            //修改article表
            int updateById = apArticleMapper.updateById(apArticle);
            if (updateById < 1){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"修改失败");
            }
            //修改article_content表
            ApArticleContent updateContent = new ApArticleContent();
            updateContent.setContent(content);
            LambdaQueryWrapper<ApArticleContent>wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId,id);
            int updateResult = apArticleContentMapper.update(updateContent, wrapper);
            if (updateResult < 1){
                log.warn("内容修改失败");
                throw  new RuntimeException("文章内容修改失败");

            }

            return ResponseResult.okResult(id);

        }

    }

    @Autowired
    private KafkaTemplate <String,String> kafkaTemplate;
    @Override
    public void  articleIndexUpdate(ApArticle apArticle,String content) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);

        vo.setPublishTime(new Date());
        vo.setContent(content);

        kafkaTemplate.send("update.topic", JSON.toJSONString(vo));


    }

    //回显
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if (dto == null) {
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long articleId = dto.getArticleId();
        Integer authorId = dto.getAuthorId();
        ApUser user = AppThreadLocalUtil.getUser();
        Integer userId = user.getId();

        Boolean isLike = false, isUnLike = false ,isCollection = false,isFollow = false;
        //islike点赞，isunlike，不喜欢，iscollection收藏，isfollow关注
        Object liked = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId.toString(), userId.toString());
        if (liked == null) {
            isLike =true;
        }

        Object unLiked = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId.toString(), userId.toString());
        if (unLiked == null) {
            isUnLike =true;
        }
        Object collection = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + articleId.toString(), userId.toString());
        if (collection == null) {
            isCollection = true;
        }
        Object Followed = cacheService.hGet(BehaviorConstants.APUSER_FOLLOW_RELATION + userId.toString(), articleId.toString());
        if (Followed == null) {
            isFollow =true;
        }

        Map<String, Object> map = new HashMap<>(4);
        map.put("islike", isLike);
        map.put("isunlike", isUnLike);
        map.put("iscollection", isCollection);
        map.put("isfollow", isFollow);

        return ResponseResult.okResult(map);



    }
}
